package com.sunda.spmsorder.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.ShoppingScenario;
import com.sunda.spmsorder.entity.ShoppingScenarioDtl;
import com.sunda.spmsorder.mapper.ShoppingScenarioDtlMapper;
import com.sunda.spmsorder.mapper.ShoppingScenarioMapper;
import com.sunda.spmsorder.service.IShoppingScenarioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * <p>
 * 请购场景表表头 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-03-01
 */
@Service
public class ShoppingScenarioServiceImpl extends ServiceImpl<ShoppingScenarioMapper, ShoppingScenario> implements IShoppingScenarioService {

    @Autowired
    ShoppingScenarioMapper shoppingScenarioMapper;

    @Autowired
    ShoppingScenarioDtlMapper shoppingScenarioDtlMapper;

    @Override
    public Map<String, Object> getScenarioList(int pageNo, int pageSize, String [] werks, String isDelete) {
        if (werks.length == 0){
            return null;
        }
        isDelete = isDelete.trim().length() == 0 ? null : isDelete.trim();
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> mapList = shoppingScenarioMapper.getScenarioList(werks, isDelete);
        PageInfo<Map<String, Object>> pageData = new PageInfo<>(mapList);
        Map<String,Object> pageInfo = new HashMap<>();
        pageInfo.put("records", pageData.getList());
        pageInfo.put("total", pageData.getTotal());
        pageInfo.put("size", pageData.getSize());
        pageInfo.put("current", pageData.getPageNum());
        pageInfo.put("pages", pageData.getPages());
        return pageInfo;
    }

    @Override
    public Map<String, Object> queryScenarioList(JSONObject queryObj) {
        String werks=queryObj.getString("werks");
        String isDelete = queryObj.getString("isDelete");
        String spmsId=StringUtil.isNotEmpty(queryObj.getString("spmsId"))? queryObj.getString("spmsId"):null;
        String authorName=StringUtil.isNotEmpty(queryObj.getString("authorName"))? queryObj.getString("authorName"):null;
        String scenarioName=StringUtil.isNotEmpty(queryObj.getString("scenarioName"))? queryObj.getString("scenarioName"):null;
        int pageNo = queryObj.getIntValue("pageNo");
        int pageSize = queryObj.getIntValue("pageSize");
        if(StringUtil.isEmpty(werks)){
            return null;
        }
        isDelete = isDelete.trim().length() == 0 ? null : isDelete.trim();
        PageHelper.startPage(pageNo, pageSize);
        String[] werksArray={werks};
        List<Map<String, Object>> mapList = shoppingScenarioMapper.queryScenarioList(werksArray, isDelete,authorName,scenarioName,spmsId);
        PageInfo<Map<String, Object>> pageData = new PageInfo<>(mapList);
        Map<String,Object> pageInfo = new HashMap<>();
        pageInfo.put("records", pageData.getList());
        pageInfo.put("total", pageData.getTotal());
        pageInfo.put("size", pageData.getSize());
        pageInfo.put("current", pageData.getPageNum());
        pageInfo.put("pages", pageData.getPages());
        return pageInfo;
    }

    @Override
    public List<Map<String, Object>> getScenarioDtlList(String uuid) {
        return shoppingScenarioDtlMapper.getScenarioDtlList(uuid);
    }

    /**
     * {
     * 	"shoppingScenario": {
     * 		"scenarioDesc": "GF01xx电机维修场景描述",
     * 		"machineDesc": "设备描述",
     * 		"createUserid": "20001",
     * 		"werks": "GF01",
     * 		"machineNo": "machine no",
     * 		"scenarioName": "GF01xx电机维修场景",
     * 		"remarks": null
     *        },
     * 	"shoppingScenarioDtl": [{
     * 			"ssdRowId": 1,
     * 			"quantity": 5,
     * 			"longContractCode": null,
     * 			"materialNo": "130014340",
     * 			"brand": null
     *        },
     *        {
     * 			"ssdRowId": 2,
     * 			"quantity": 6,
     * 			"longContractCode": null,
     * 			"materialNo": "130011913",
     * 			"brand": null
     *        }
     * 	]
     * }
     * @param doc
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult createScenario(JSONObject doc) {
        if (!doc.containsKey("shoppingScenario") || doc.get("shoppingScenario") == null){
            return ResponseResult.error("请求参数错误");
        }
        if (!doc.containsKey("shoppingScenarioDtl")){
            return ResponseResult.error("请求参数错误");
        }
        try{
            JSONObject shoppingScenario = doc.getJSONObject("shoppingScenario");
            JSONArray shoppingScenarioDtl = doc.getJSONArray("shoppingScenarioDtl");
            String uuid = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();

            /** 创建请购场景表头 */
            createScenario(shoppingScenario, uuid);

            /** 创建请购场景明细 */
            createScenarioDtl(shoppingScenarioDtl, uuid);

            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    void createScenario(JSONObject shoppingScenario, String uuid){
        ShoppingScenario scenario = new ShoppingScenario();
        scenario.setUuid(uuid);
        scenario.setWerks(shoppingScenario.getString("werks"));
        scenario.setScenarioName(shoppingScenario.getString("scenarioName"));
        scenario.setScenarioDesc(shoppingScenario.getString("scenarioDesc"));
        scenario.setMachineNo(shoppingScenario.getString("machineNo"));
        scenario.setMachineDesc(shoppingScenario.getString("machineDesc"));
        scenario.setRemarks(shoppingScenario.getString("remarks"));
        scenario.setCreateUserid(shoppingScenario.getString("createUserid"));
        shoppingScenarioMapper.insert(scenario);
    }

    void createScenarioDtl(JSONArray shoppingScenarioDtl, String uuid){
        if (shoppingScenarioDtl.size() > 0){
            for (int i = 0; i < shoppingScenarioDtl.size(); i ++){
                JSONObject dtl = shoppingScenarioDtl.getJSONObject(i);
                ShoppingScenarioDtl scenarioDtl = new ShoppingScenarioDtl();
                scenarioDtl.setUuid(uuid);
                scenarioDtl.setSsdRowId(Integer.parseInt(dtl.getString("ssdRowId")));
                scenarioDtl.setMaterialNo(dtl.getString("materialNo"));
                scenarioDtl.setQuantity(Double.parseDouble(dtl.getString("quantity")));
                scenarioDtl.setLongContractCode(dtl.getString("longContractCode"));
                scenarioDtl.setBrand(dtl.getString("brand"));
                shoppingScenarioDtlMapper.insert(scenarioDtl);
            }
        }

    }

    /***
     * {
     * 	"uuid": "429ecfbda9ba43e8a03b90945300f568",
     * 	"werks": "GF01",
     * 	"scenarioId": "GF01-0002",
     * 	"scenarioName": "GF01xx电机维修场景",
     * 	"scenarioDesc": "GF01xx电机维修场景描述",
     * 	"machineNo": "machine no",
     * 	"machineDesc": "设备描述",
     * 	"remarks": null,
     * 	"isDelete": "0",
     * 	"updateUser": "20001"
     * }
     * @param doc
     * @return
     */
    @Override
    public ResponseResult updateScenario(JSONObject doc) {
        if (!doc.containsKey("uuid") || doc.getString("uuid").length() == 0){
            return ResponseResult.error("请求参数错误");
        }
        ShoppingScenario shoppingScenario = new ShoppingScenario();
        shoppingScenario.setScenarioName(doc.getString("scenarioName"));
        shoppingScenario.setScenarioDesc(doc.getString("scenarioDesc"));
        shoppingScenario.setMachineNo(doc.getString("machineNo"));
        shoppingScenario.setMachineDesc(doc.getString("machineDesc"));
        shoppingScenario.setRemarks(doc.getString("remarks"));
        shoppingScenario.setIsDelete(doc.getString("isDelete"));
        shoppingScenario.setUpdateUserid(doc.getString("updateUser"));
        int resp = shoppingScenarioMapper.update(shoppingScenario, new QueryWrapper<ShoppingScenario>().eq("UUID", doc.getString("uuid")));
        if (resp > 0){
            return ResponseResult.success();
        }
        return ResponseResult.error();
    }

    /***
     * {
     * 	"uuid": "9463644cb2a941c881e88c76d12b62fw",
     * 	"shoppingScenarioDtl": [{
     * 			"ssdRowId": 1,
     * 			"quantity": 5,
     * 			"longContractCode": null,
     * 			"materialNo": "130014340",
     * 			"brand": null
     *        },
     *        {
     * 			"ssdRowId": 2,
     * 			"quantity": 6,
     * 			"longContractCode": null,
     * 			"materialNo": "130011913",
     * 			"brand": null
     *        }]
     * }
     * @param doc
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateScenarioDtl(JSONObject doc) {
        if (!doc.containsKey("uuid") || doc.getString("uuid") == ""){
            return ResponseResult.error("请求参数错误");
        }
        if (!doc.containsKey("shoppingScenarioDtl")){
            return ResponseResult.error("请求参数错误");
        }
        try {
            String uuid = doc.getString("uuid");
            /** 根据 uuid 删除请购场景明细数据 */
            shoppingScenarioDtlMapper.delete(new QueryWrapper<ShoppingScenarioDtl>().eq("UUID", uuid));

            /** 根据传入明细数据新建场景明细 */
            createScenarioDtl(doc.getJSONArray("shoppingScenarioDtl"), uuid);
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @Override
    public ResponseResult deleteScenarios(String[] scenarioUuid) {
        try {
            int resp = shoppingScenarioMapper.deleteScenarios(scenarioUuid);
            return ResponseResult.success();
        }catch (Exception e){
            return ResponseResult.error();
        }
    }
}
